﻿using System;
using System.IO;
using System.Xml.Serialization;
using Caliburn.Micro;

namespace PocketBook.Tasks
{
    public class SerializationTask<T> : IResult where T : class
    {
        public string FileName { get; set; }

        public T Source { get; set; }

        public event EventHandler<ResultCompletionEventArgs> Completed;

        public void Execute(ActionExecutionContext context)
        {
            try
            {
                using (TextWriter writer = new StreamWriter(FileName))
                {
                    new XmlSerializer(typeof(T)).Serialize(writer, Source);
                }

                Completed(this, new ResultCompletionEventArgs());
            }
            catch (Exception exception)
            {
                Completed(this, new ResultCompletionEventArgs { Error = exception });
            }
        }
    }
}